const router = require('koa-router')();
const { exec } = require('../db/index')
const { getPassword } = require('../utils/crypto')

router.prefix('/api')
// 定义返回模型

const SuccessModel = {
  code: 0,
  msg: 'success'
}
const FailModel = {
  code: 0,
  msg: 'fail'
}

// 登陆  注册  增 删 改 查


router.post('/login', async (ctx, next) => {
  // 获取 账号 密码 匹配数据库
  const { username, password } = ctx.request.body;
  // 如果是字符串 ，一定要加引号
  let data = await exec(`select * from users where username='${username}' and password='${getPassword(password)}'`)
  if (data.length) {
    ctx.body = { ...SuccessModel, data }
  } else {
    ctx.body = { ...FailModel, tip: '请注册' }
  }
})

// 注册 
router.post('/register', async (ctx, next) => {
  // 获取参数
  const { username, password, nickname } = ctx.request.body;
  let data = await exec(`select * from users where username='${username}' and password='${getPassword(password)}'`)
  if (data.length) {
    ctx.body = { ...FailModel, tip: '用户名已经存在' }
  } else {
    let insertData = await exec(`insert into users (username, password, nickname) values ('${username}','${getPassword(password)}', '${nickname}')`)
    // 返回增加的数据id
    ctx.body = { ...SuccessModel, insertId: insertData.insertId }
  }
})

// 操作 blogs
router.post('/add', async (ctx, next) => {
  const { title, content, author, userid } = ctx.request.body;
  let data = await exec(`insert into blogs (title, content, author, userid) values ('${title}','${content}','${author}', ${userid})`)
  // 返回增加的数据id
  ctx.body = { ...SuccessModel, id: data.insertId };
})

router.delete('/delete', async (ctx, next) => {
  const { id } = ctx.request.body;
  let data = await exec(`delete from blogs where id=${id}`)
  // 返回影响了几行
  ctx.body = { ...SuccessModel, affectedRows: data.affectedRows }
})

router.get('/findAll', async (ctx, next) => {
  let data = await exec(`select title, content,createtime from blogs`)
  // 返回查到的所有数据
  ctx.body = { ...SuccessModel, data };
})

router.put('/update', async (ctx, next) => {
  // 需要知道自己更新哪一条数据 id
  const { title, content, author, userid, id } = ctx.request.body;
  let data = await exec(`update blogs set title='${title}', content='${content}',author='${author}',userid=${userid} where id=${id}`)
  // 告诉用户，影响了几行
  ctx.body = { ...SuccessModel, affectedRows: data.affectedRows }
})




module.exports = router;